package thread.cf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {


        // 构造自定义线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);

        System.out.println(Thread.currentThread().getName());

        // runAsync, 执行逻辑没有返回值
        CompletableFuture<Void> runAsyncResult =
                CompletableFuture.runAsync(() -> {
                    System.out.println(Thread.currentThread().getName());
                    System.out.println(123456);
                },executor);


        CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> "123",executor);
//        System.out.println("f1.get() = " + Thread.currentThread().getName()+","+f1.get());

        System.out.println("f1 = " + f1);

        CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
                System.out.println("5秒之后");
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "124";
        },executor);

        CompletableFuture<String> f3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(10000);
                System.out.println("10秒之后");
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "124";
        },executor);
//        System.out.println("f2.get() = " + Thread.currentThread().getName()+","+f2.get());
        System.out.println("f2 = " + f2);
        f3.join();
//        CompletableFuture.allOf(f1).join();
        System.out.println("f1 = " + f1);
        System.out.println("f2 = " + f2);
        System.out.println("f3 = " + f3);

        executor.shutdown();



   /*     CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("supplyAsync excetion occurred...");
        }).handle((obj, e) -> {
            if (e != null) {
                System.out.println("thenApply executed, exception occurred...");
            }
            return obj;
        }).join();*/
    }
}
